package com.kunya.common.common;

import com.kunya.common.exception.ServerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zp
 * @Description:
 * @date 2018/5/25 10:09
 */
@Component
@Slf4j
public class ExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        log.error("{}Exception",httpServletRequest.getRequestURI(),e);
        ModelAndView modelAndView= new ModelAndView(new MappingJackson2JsonView());
        modelAndView.addObject("status",ResponseCode.ERROR.getCode());
        modelAndView.addObject("msg","接口异常");
        //如果是服务异常就只返回错误信息,否则返回异常的toString
        modelAndView.addObject("data",(e instanceof ServerException)? e.getMessage():e.toString());
        return modelAndView;
    }
}
